package com.zidongxiangxi.rabbit.producer.util;

import com.zidongxiangxi.rabbit.producer.entity.RabbitCorrelationId;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * 发送端工具类
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class ProducerUtils {
	public static CorrelationData generateCorrelationData(String application, String messageId) {
		if (StringUtils.isEmpty(application)
				|| StringUtils.isEmpty(messageId)) {
			return null;
		}
		RabbitCorrelationId rabbitCorrelationId = new RabbitCorrelationId(application, messageId);
		CorrelationData correlationData = new CorrelationData();
		correlationData.setId(rabbitCorrelationId.toString());
		return correlationData;
	}

	public static <T> Optional<T> tryGetFirstArg(Object[] args, Class<?>[] argTypes, Class<T> targetClass) {
		if (isInvalidArgsAndTypes(args, argTypes)) {
			return null;
		}
		for (int i = 0; i < args.length; i++) {
			if (Objects.equals(argTypes[i], targetClass)) {
				return Optional.ofNullable((T)args[i]);
			}
		}
		return null;
	}

	public static <T> Optional<T> tryGetSecondArg(Object[] args, Class<?>[] argTypes, Class<T> targetClass) {
		if (isInvalidArgsAndTypes(args, argTypes)) {
			return null;
		}
		boolean foundFirstString = false;
		for (int i = 0; i < args.length; i++) {
			if (Objects.equals(argTypes[i], targetClass)) {
				if (foundFirstString) {
					return Optional.ofNullable((T)args[i]);
				} else {
					foundFirstString = true;
				}
			}
		}
		return null;
	}

	private static boolean isInvalidArgsAndTypes(Object[] args, Class<?>[] argTypes) {
		return Objects.isNull(args)
				|| Objects.isNull(argTypes)
				|| args.length != argTypes.length
				|| args.length < 1;
	}
}
